package com.threeonemeeting.activity;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

import com.snda.lib.util.MiscHelper;
import com.threeonemeeting.R;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.util.MiscUtil;
import com.weibo.sina.OAuthConstant;
import com.weibo.sina.WeiboException;
import com.weibo.sina.http.AccessToken;
import com.weibo.sina.http.RequestToken;
import com.weibo.tencent.QWeibo;

public class WeiboCallbackActivity extends BaseTabActivity {

	private TextView tx = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_weibo_callback);
		init("微博绑定");
		tx = (TextView) findViewById(R.id.success_txt);

		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras == null)
			return;

		String strFrom = extras.getString("from");
		if (MiscHelper.isEmpty(strFrom) == true)
			return;

		String strUri = this.getIntent().getStringExtra("uri");
		Uri uri = Uri.parse(strUri);

		if (strFrom.equalsIgnoreCase("sina") == true) {

			RequestToken requestToken = OAuthConstant.getInstance()
					.getRequestToken();
			AccessToken accessToken;
			try {
				accessToken = requestToken.getAccessToken(uri
						.getQueryParameter("oauth_verifier"));
				OAuthConstant.getInstance().setAccessToken(accessToken);

				if (accessToken != null) {
					MiscUtil.setPrefer("SinaWeiboToken", accessToken.getToken());
					MiscUtil.setPrefer("SinaWeiboSecret",
							accessToken.getTokenSecret());
				}

				if (tx != null) {
					tx.setText("新浪微博帐号绑定成功");
				}
			} catch (WeiboException e) {
				if (tx != null) {
					tx.setText("新浪微博帐号绑定失败");
				}
			}

		} else if (strFrom.equalsIgnoreCase("qq") == true) {

			String oauth_verifier = uri.getQueryParameter("oauth_verifier");

			String strAccessToken = QWeibo.getInstance().requestAccessToken(
					oauth_verifier);
			if (MiscHelper.isEmpty(strAccessToken) == true) {
				if (tx != null) {
					tx.setText("腾讯微博帐号绑定失败");
				}

				return;
			}

			MiscUtil.setPrefer("QQWeiboToken", QWeibo.getInstance()
					.getAccessToken());
			MiscUtil.setPrefer("QQWeiboSecret", QWeibo.getInstance()
					.getAccessTokenSecret());

			TextView tx = (TextView) findViewById(R.id.success_txt);
			if (tx != null) {
				tx.setText("腾讯微博帐号绑定成功");
			}
		}

	}

	@Override
	public void back() {
		this.startActivity("WeiboAccountActivity");
	}
}
